package cn.e4j.modular.crm.controller;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.e4j.config.properties.E4jProperties;
import cn.e4j.core.base.controller.BaseController;
import cn.e4j.core.common.exception.BizExceptionEnum;
import cn.e4j.core.dto.Dtos;
import cn.e4j.core.dto.impl.Dto;
import cn.e4j.core.dto.requestDtoResolver.DtoParam;
import cn.e4j.core.dto.requestDtoResolver.DtoWapper;
import cn.e4j.core.reqres.response.ErrorResponseData;
import cn.e4j.core.reqres.response.PageReData;
import cn.e4j.core.reqres.response.ResponseData;
import cn.e4j.core.reqres.response.SuccessResponseData;
import cn.e4j.core.shiro.ShiroKit;
import cn.e4j.core.shiro.ShiroUser;
import cn.e4j.core.util.LangUtils;
import cn.e4j.modular.crm.entity.*;
import cn.e4j.modular.crm.mapper.GwaeTMapper;
import cn.e4j.modular.crm.mapper.GwakTMapper;
import cn.e4j.modular.crm.mapper.GwamTMapper;
import cn.e4j.modular.crm.mapper.GwdczTMapper;
import cn.e4j.modular.crm.service.impl.Gwdc004ServiceImpl;
import cn.e4j.modular.utils.CrmExceptionEnum;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 组合促销价格维护管理
 * Created by shixc on 2019-1-28.
 */
@Controller
@RequestMapping("/crm/gwdc004")
public class Gwdc004Controller extends BaseController {

    @Autowired
    private Gwdc004ServiceImpl gwdc004Service;

    @Autowired
    private E4jProperties e4jProperties;

    @Autowired
    private GwakTMapper gwakTMapper;

    @Autowired
    private GwamTMapper gwamTMapper;

    @Autowired
    private GwdczTMapper gwdczTMapper;

    @Autowired
    private GwaeTMapper gwaeTMapper;

    /**
     * 跳转组合促销价格管理页面
     */
    @RequiresPermissions("crm:gwdc004:init")
    @RequestMapping(value = {"", "init"})
    public String index() {
        return "/pc/crm/gwdc004.html";
    }

    /**
     * 查询组合促销价格信息列表
     */
    @RequestMapping("/getList")
    @RequiresPermissions("crm:gwdc004:init")
    @ResponseBody
    public ResponseData getList(@DtoParam DtoWapper dtoWapper) {
        Page<Object> page = dtoWapper.getPage();
        ShiroUser shiroUser = ShiroKit.getUser();
        Dto inDto = dtoWapper.getDto();
        inDto.put("GWDCENT", shiroUser.getDBC());
        List<Map<String, Object>> result = gwdc004Service.getListData(page, inDto);
        return new PageReData(page, result);
    }

    /**
     * 获取新增活动编号
     */
    @RequestMapping("/getGwdc001")
    @RequiresPermissions("crm:gwdc004:init")
    @ResponseBody
    public ResponseData getGwdc001(@DtoParam DtoWapper dtoWapper) {
        ShiroUser shiroUser = ShiroKit.getUser();
        Dto inDto = dtoWapper.getDto();
        inDto.put("ENT", shiroUser.getDBC());
        inDto.put("LANG", LangUtils.getLang(shiroUser.getLANG()));
        Dto addDataDto = gwdc004Service.getGwdc001(inDto);
        return new SuccessResponseData(addDataDto);
    }

    /**
     * 获取活动结算价
     */
    @RequestMapping("/getGwdb")
    @RequiresPermissions("crm:gwdc004:init")
    @ResponseBody
    public ResponseData getGwdb(@DtoParam DtoWapper dtoWapper) {
        Dto inDto = dtoWapper.getDto();
        List<GwdcT> gwdcTList = inDto.getReqList(GwdcT.class);
        List<Dto> list = gwdc004Service.getGwdb(gwdcTList);
        return new SuccessResponseData(list);
    }

    /**
     * 新增
     */
    @RequestMapping("/addData")
    @RequiresPermissions("crm:gwdc004:init")
    @ResponseBody
    public ResponseData addData(@DtoParam DtoWapper dtoWapper) {
        Dto inDto = dtoWapper.getDto();
        JSONObject jsonObject = inDto.getReqJsonObject();
        List<GwdcT> gwdcTList = JSONObject.parseArray(jsonObject.getString("list1"), GwdcT.class);
        List<GwdczT> gwdczTList = JSONObject.parseArray(jsonObject.getString("list2"), GwdczT.class);
        List<GwdctT> gwdctTList = JSONObject.parseArray(jsonObject.getString("list3"), GwdctT.class);
        Dto dto = gwdc004Service.addData(gwdcTList, gwdczTList, gwdctTList);
        if (dto.getAppCode() == 400) {
            return new ErrorResponseData(CrmExceptionEnum.EXISTED_THE_GWDC.getCode(),
                    CrmExceptionEnum.EXISTED_THE_GWDC.getMessage());
        } else if (dto.getAppCode() == 401) {
            return new ErrorResponseData(CrmExceptionEnum.EXISTED_THE_GWDCZ.getCode(),
                    CrmExceptionEnum.EXISTED_THE_GWDCZ.getMessage());
        }
        return SUCCESS_TIP;
    }

    /**
     * 删除
     */
    @RequestMapping("/del")
    @RequiresPermissions("crm:gwdc004:init")
    @ResponseBody
    public ResponseData del(GwdcT gwdcT) {
        gwdc004Service.delete(gwdcT);
        return SUCCESS_TIP;
    }

    /**
     * 批量删除数据
     */
    @RequestMapping("/deleteDataBatch")
    @RequiresPermissions("crm:gwdc004:init")
    @ResponseBody
    public ResponseData deleteDataBatch(@DtoParam DtoWapper dtoWapper) {
        Dto inDto = dtoWapper.getDto();
        List<GwdcT> gwdcTList = inDto.getReqList(GwdcT.class);
        gwdc004Service.delDataBatch(gwdcTList);
        return SUCCESS_TIP;
    }

    /**
     * 批量审核数据
     */
    @RequestMapping("/check")
    @RequiresPermissions("crm:gwdc004:init")
    @ResponseBody
    public ResponseData check(@DtoParam DtoWapper dtoWapper) {
        Dto inDto = dtoWapper.getDto();
        List<GwdcT> gwdcTList = inDto.getReqList(GwdcT.class);
        gwdc004Service.check(gwdcTList);
        return SUCCESS_TIP;
    }

    /**
     * 批量取消审核数据
     */
    @RequestMapping("/unCheck")
    @RequiresPermissions("crm:gwdc004:init")
    @ResponseBody
    public ResponseData unCheck(@DtoParam DtoWapper dtoWapper) {
        Dto inDto = dtoWapper.getDto();
        List<GwdcT> gwdcTList = inDto.getReqList(GwdcT.class);
        gwdc004Service.unCheck(gwdcTList);
        return SUCCESS_TIP;
    }

    /**
     * 查询商品信息列表
     */
    @RequestMapping("/listGwdc")
    @RequiresPermissions("crm:gwdc004:init")
    @ResponseBody
    public ResponseData listGwdc(@DtoParam DtoWapper dtoWapper) {
        ShiroUser shiroUser = ShiroKit.getUser();
        Dto inDto = dtoWapper.getDto();
        inDto.put("GWDCENT", shiroUser.getDBC());
        inDto.put("lang", LangUtils.getLang(shiroUser.getLANG()));
        List<Map<String, Object>> result = gwdc004Service.listGwdc(inDto);
        return ResponseData.success(result);
    }

    /**
     * 查询赠品信息列表
     */
    @RequestMapping("/listGwdcz")
    @RequiresPermissions("crm:gwdc004:init")
    @ResponseBody
    public ResponseData listGwdcz(@DtoParam DtoWapper dtoWapper) {
        ShiroUser shiroUser = ShiroKit.getUser();
        Dto inDto = dtoWapper.getDto();
        inDto.put("GWDCZENT", shiroUser.getDBC());
        inDto.put("lang", LangUtils.getLang(shiroUser.getLANG()));
        List<Map<String, Object>> result = gwdc004Service.listGwdcz(inDto);
        return ResponseData.success(result);
    }

    /**
     * 查询gwdct信息列表
     */
    @RequestMapping("/listGwdct")
    @RequiresPermissions("crm:gwdc004:init")
    @ResponseBody
    public ResponseData listGwdct(@DtoParam DtoWapper dtoWapper) {
        Dto inDto = dtoWapper.getDto();
        List<Map<String, Object>> result = gwdc004Service.listGwdct(inDto);
        return ResponseData.success(result);
    }

    /**
     * 修改
     */
    @RequestMapping("/editData")
    @RequiresPermissions("crm:gwdc004:init")
    @ResponseBody
    public ResponseData editData(@DtoParam DtoWapper dtoWapper) {
        Dto inDto = dtoWapper.getDto();
        JSONObject jsonObject = inDto.getReqJsonObject();
        List<GwdcT> gwdcTList = JSONObject.parseArray(jsonObject.getString("list1"), GwdcT.class);
        List<GwdczT> gwdczTList = JSONObject.parseArray(jsonObject.getString("list2"), GwdczT.class);
        List<GwdctT> gwdctTList = JSONObject.parseArray(jsonObject.getString("list3"), GwdctT.class);
        Dto dto = gwdc004Service.editData(gwdcTList, gwdczTList, gwdctTList);
        if (dto.getAppCode() == 400) {
            return new ErrorResponseData(CrmExceptionEnum.EXISTED_THE_GWDC.getCode(),
                    CrmExceptionEnum.EXISTED_THE_GWDC.getMessage());
        } else if (dto.getAppCode() == 401) {
            return new ErrorResponseData(CrmExceptionEnum.EXISTED_THE_GWDCZ.getCode(),
                    CrmExceptionEnum.EXISTED_THE_GWDCZ.getMessage());
        }
        return SUCCESS_TIP;
    }

    /**
     * 展期修改
     */
    @RequestMapping("/edit")
    @RequiresPermissions("crm:gwdc004:init")
    @ResponseBody
    public ResponseData edit(GwdcT gwdcT) {
        gwdc004Service.edit(gwdcT);
        return SUCCESS_TIP;
    }

//    @RequestMapping(value = "/exportsData", method = RequestMethod.GET)
//    @RequiresPermissions("crm:gwdc004:init")
//    public void exportsData(ModelMap map, HttpServletRequest request, HttpServletResponse response,@DtoParam DtoWapper dtoWapper) {
//        Dto inDto = dtoWapper.getDto();
//        ShiroUser user = ShiroKit.getUser();
//        inDto.put("lang", LangUtils.getLang(user.getLANG()));
//        inDto.put("GWDCENT", user.getDBC());
//        List<Map<String, Object>> list = gwdc004Service.getListData(null, inDto);
//        ExportParams params = new ExportParams(null, "组合促销价格数据", ExcelType.XSSF);
//        //params.setFreezeCol(2);
//        map.put(NormalExcelConstants.FILE_NAME, "组合促销价格数据");
//        map.put(NormalExcelConstants.DATA_LIST, list);
//        map.put(NormalExcelConstants.CLASS, Gwdc004Export.class);
//        map.put(NormalExcelConstants.PARAMS, params);
//        PoiBaseView.render(map, request, response, NormalExcelConstants.EASYPOI_EXCEL_VIEW);
//    }

    @RequestMapping(value = "/importsData", method = RequestMethod.POST)
    @RequiresPermissions("crm:gwdc004:init")
    @ResponseBody
    public ResponseData importsData(MultipartFile file, ModelMap map, String GWDC007, String GWDC008) {
        ShiroUser user = ShiroKit.getUser();
        List<Dto> result = new ArrayList<>();
        Dto inDto = Dtos.newDto();
        ImportParams params = new ImportParams();
        params.setTitleRows(0);//表格标题行数,默认0
        params.setHeadRows(1);//表头行数,默认1
        params.setStartRows(0);//字段真正值和列标题之间的距离 默认0
        int count = 0;
        String message1 = "客户";
        String message2 = "渠道";
        String message3 = "品号";
        String message4 = "商品";
        try {
            List<GwdcT> list = ExcelImportUtil.importExcel(file.getInputStream(), GwdcT.class, params);
            for (GwdcT gwdcT : list) {
                LocalDate beginDateTime = LocalDate.parse(GWDC008, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                gwdcT.setGWDC008(beginDateTime);
                if (gwdcT.getGWDC016() != null && gwdcT.getGWDC018() != null && gwdcT.getGWDC024() != null) {//客户、品号、促销价格不为空
                    int gwak = 0;
                    if (GWDC007.equals("2")) {
                        QueryWrapper<GwakT> gwakTUpdateWrapper = new QueryWrapper<>();
                        gwakTUpdateWrapper.eq("GWAKENT", user.getDBC());
                        gwakTUpdateWrapper.eq("GWAK001", gwdcT.getGWDC016());
                        gwak = gwakTMapper.selectList(gwakTUpdateWrapper).size();
                    } else if (GWDC007.equals("1")) {
                        QueryWrapper<GwaeT> gwaeTUpdateWrapper = new QueryWrapper<>();
                        gwaeTUpdateWrapper.eq("GWAEENT", user.getDBC());
                        gwaeTUpdateWrapper.eq("GWAE001", gwdcT.getGWDC016());
                        gwak = gwaeTMapper.selectList(gwaeTUpdateWrapper).size();
                    }
                    int gwam = 0;
                    QueryWrapper<GwamT> gwamTUpdateWrapper = new QueryWrapper<>();
                    gwamTUpdateWrapper.eq("GWAMENT", user.getDBC());
                    gwamTUpdateWrapper.eq("GWAM001", gwdcT.getGWDC018());
                    gwam = gwamTMapper.selectList(gwamTUpdateWrapper).size();
                    List<Dto> gwdb = new ArrayList<>();
                    if (gwak > 0 && gwam > 0) {
                        Dto pDto = Dtos.newDto();
                        if (GWDC007.equals("2")) {
                            pDto = gwdczTMapper.getGwdb(user.getDBC(), GWDC007, gwdcT.getGWDC016(), gwdcT.getGWDC018(), gwdcT.getGWDC008());
                        } else if (GWDC007.equals("1")) {
                            pDto = gwdczTMapper.getGwdb2(user.getDBC(), GWDC007, gwdcT.getGWDC016(), gwdcT.getGWDC018(), gwdcT.getGWDC008());
                        }
                        if (pDto != null) {
                            gwdb.add(pDto);
                        } else {
                            if (GWDC007.equals("2")) {
                                Dto dto = gwdczTMapper.getGwak010(user.getDBC(), gwdcT.getGWDC016());
                                if (dto != null) {
                                    Dto sDto = gwdczTMapper.getGwdb(user.getDBC(), "1", dto.getString("GWAK010"), gwdcT.getGWDC018(), gwdcT.getGWDC008());
                                    if (sDto != null) {
                                        gwdb.add(sDto);
                                    }
                                }
                            }
                        }
                        if (gwdb.size() > 0) {
                            Dto dto = Dtos.newDto();
                            dto.put("GWDC016", gwdcT.getGWDC016());
                            dto.put("GWDC017", gwdb.get(0).getString("GWAKL004"));
                            dto.put("GWDC018", gwdb.get(0).getString("GWAM001"));
                            dto.put("GWAML003", gwdb.get(0).getString("GWAML003"));
                            dto.put("GWAML004", gwdb.get(0).getString("GWAML004"));
                            dto.put("GWDC019", gwdb.get(0).getString("GWAM008"));
                            dto.put("GWDC023", gwdb.get(0).getString("GWDB016"));
                            dto.put("GWDC024", gwdcT.getGWDC024());
                            result.add(dto);
                            count++;
                        } else {
                            message4 = message4 + gwdcT.getGWDC018() + ",";
                        }
                    } else {
                        if (gwak == 0 && GWDC007.equals("2")) {
                            message1 = message1 + gwdcT.getGWDC016() + ",";
                        } else if (gwak == 0 && GWDC007.equals("1")) {
                            message2 = message2 + gwdcT.getGWDC016() + ",";
                        }
                        if (gwam == 0) {
                            message3 = message3 + gwdcT.getGWDC018() + ",";
                        }
                        continue;
                    }
                } else {
                    continue;
                }
            }
            if (count != list.size()) {
                if (!message1.equals("客户")) {
                    message1 = message1.substring(0, message1.length() - 1);
                    message1 = message1 + "不存于有效的客户资料中,";
                } else {
                    message1 = "";
                }
                if (!message2.equals("渠道")) {
                    message2 = message2.substring(0, message2.length() - 1);
                    message2 = message2 + "不存于有效的渠道资料中,";
                } else {
                    message2 = "";
                }
                if (!message3.equals("品号")) {
                    message3 = message3.substring(0, message3.length() - 1);
                    message3 = message3 + "不存于有效的产品资料中,";
                } else {
                    message3 = "";
                }
                if (!message4.equals("商品")) {
                    message4 = message4.substring(0, message4.length() - 1);
                    message4 = message4 + "未设置结算价,";
                } else {
                    message4 = "";
                }
                String message = "";
                if (count > 0) {
                    message = message1 + message2 + message3 + message4 + "请检查!有" + count + "笔导入成功。";
                    return new ErrorResponseData(300,
                            message, result);
                } else {
                    message = message1 + message2 + message3 + message4 + "请检查!";
                    return new ErrorResponseData(401,
                            message);
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
            return new ErrorResponseData(BizExceptionEnum.SERVER_ERROR.getCode(),
                    BizExceptionEnum.SERVER_ERROR.getMessage());
        }
        return ResponseData.success(300, "请求成功", result);
    }

    @RequestMapping("/getGwdc001Data")
    @ResponseBody
    public ResponseData getGwdc001Data(@DtoParam DtoWapper dtoWapper) {
        Page<Object> page = dtoWapper.getPage();
        Dto inDto = dtoWapper.getDto();
        List<Map<String, Object>> result = gwdc004Service.getGwdc001Data(page, inDto);
        return new PageReData(page, result);
    }

}
